package com.pams.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.pams.handler.BaseException;
import com.pams.mapper.UserMapper;
import com.pams.pojo.dto.LoginDTO;
import com.pams.pojo.dto.RegisterDTO;
import com.pams.pojo.entity.User;
import com.pams.pojo.vo.LoginVO;
import com.pams.properties.JwtProperties;
import com.pams.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserService {
    @Autowired
    UserMapper  userMapper;
    @Autowired
    JwtProperties jwtProperties;

    public void register(RegisterDTO registerDTO) {
        if(userMapper.selectByUsername(registerDTO.getUsername()) != null){
            throw new BaseException("账号已存在");
        }
        registerDTO.setPassword((SecureUtil.md5(registerDTO.getPassword())));
        userMapper.save(registerDTO);
    }

    public LoginVO login(LoginDTO loginDTO) {
        User user = userMapper.selectByUsername(loginDTO.getUsername());
        if(user == null){
            throw new BaseException("账号不存在");
        }
        String password = SecureUtil.md5(loginDTO.getPassword());
        if(!user.getPassname().equals(password)){
            throw new BaseException("密码或账号错误");
        }
        LoginVO loginVO = new LoginVO();
        BeanUtils.copyProperties(user,loginVO);

        String token = JWT.create().setPayload("username", loginDTO.getUsername())
                .setPayload("ttl", System.currentTimeMillis() + jwtProperties.getUserTtl())
                .setKey(jwtProperties.getUserSecretKey().getBytes())
                .sign();
        loginVO.setToken(token);
        return loginVO;
    }
}
